﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DHQGHN.Common;
using DHQGHN.DAL.BO.Admin;
using DHQGHN.DAL.Common;
using DHQGHN.MVC.Controllers;
using DHQGHN.PM0.Common.Attributes;
using DHQGHN.PM0.Common.Helpers;
using DHQGHN.PM0.Models.Admin;
//using DHQGHN.DAL.Models.Admin;

namespace DHQGHN.PM0.Controllers.Admin
{
    public class ApplicationController : BaseController
    {
        ApplicationBO appBO;
        log4net.ILog logger = log4net.LogManager.GetLogger(typeof(ApplicationController));
        /// <summary>
        /// Action khoi tao man hinh quan ly ung dung
        /// </summary>
        /// <param name="aModel">App model</param>
        /// <param name="pageIndex">So thu tu trang du lieu</param>
        /// <param name="sort">Truong thong tin dung de sap xep</param>
        /// <param name="sortDir">Kieu sap xep</param>
        /// <param name="currentId">Khoa ban ghi</param>
        /// <returns>Tra ve man hinh quan ly ung dung</returns>
        public ActionResult Index(ApplicationModel aModel = null, int pageIndex = 0, string sort = "AppId", string sortDir = "ASC", int currentId = -1)
        {
            try
            {
                if (aModel == null) aModel = new ApplicationModel();
                SetActiveMenu("/Application/Index");
                var model = search(aModel, pageIndex, currentId);
                return View("~/Views/Application/Application.cshtml", model);
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        /// <summary>
        /// Action chuan bi du lieu cho Them moi/Cap nhat ung dung
        /// </summary>
        /// <param name="appId">Ma ung dung</param>
        /// <returns>Trang Them moi/Cap nhat ung dung</returns>
        [HttpPost]
        public ActionResult actionPrepareCreateOrUpdateApp(int? appId)
        {
            try
            {               
                ApplicationModel app = null;
                if (appId != null && appId > 0)
                {
                    //Lay thong tin Ung dung tu Database
                    appBO = new ApplicationBO();
                    app = new ApplicationModel(appBO.GetAppById(appId));
                }
                if (app == null)
                {
                    //Khoi tao thong tin Ung dung
                    app = new ApplicationModel()
                    {
                        AppName = "",
                        AppCode = "",
                        AppDescription = "",
                        AppId = 0,
                        IsActive = 1
                    };
                }
                if (Request.IsAjaxRequest())
                {
                    return PartialView("~/Views/Application/_AppModel.cshtml", app);
                }
                return View(app);
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        /// <summary>
        /// Action Tim kiem ung dung
        /// </summary>
        /// <param name="aModel"></param>
        /// <param name="pageIndex"></param>
        /// <param name="sort"></param>
        /// <param name="sortDir"></param>
        /// <param name="currentId"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult actionSearch(ApplicationModel aModel = null, int pageIndex = 0, string sort = "AppId", string sortDir = "ASC", int currentId = -1)
        {
            try
            {
                if (aModel == null) aModel = new ApplicationModel();
                var model = search(aModel, pageIndex, currentId);
                return PartialView("~/Views/Application/_AppList.cshtml", model);
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }

        }

        /// <summary>
        /// Action Them moi ung dung
        /// </summary>
        /// <param name="model">Thong tin ung dung</param>
        /// <returns></returns>
        [HttpPost]
        [AjaxValidateAntiForgeryToken]
        [ValidateInput(false)]
        public ActionResult actionCreateOrUpdateApp(ApplicationModel model)
        {
            try
            {
                if (model == null)
                    model = new ApplicationModel();

                if (Request.IsAjaxRequest())
                {
                    appBO = new ApplicationBO();
                    //Them moi/Cap nhat ung dung
                    bool result = appBO.createOrUpdateApp(model.toDALModel());
                    if (result)
                    {
                        //Thong bao luu du lieu thanh cong
                        LogStream.Write<ApplicationModel>(GetCurrentUserName(),
                            CommonData.AppName,
                            GetFunction(),
                            Resources.Localization.ActionSaveUpdateCaption + " - actionCreateOrUpdateApp", model);

                        return Json(JsonResponse.Json200(Resources.Localization.Confirm_Save_Success));
                    }
                    else
                    {
                        //Thong bao xay ra loi trong qua trinh xu lý
                        return Json(JsonResponse.Json500(Resources.Localization.Confirm_Save_Error));
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
            return null;
        }

        /// <summary>
        /// Action xoa ung dung
        /// </summary>
        /// <param name="ids">Danh sach ma khoa ung dung</param>
        /// <returns>Ket qua xoa ung dung</returns>
        [HttpPost]
        [AjaxValidateAntiForgeryToken]
        public ActionResult actionDelete(int[] ids)
        {
            try
            {
                if (Request.IsAjaxRequest())
                {
                    appBO = new ApplicationBO();
                    bool result = true;
                    result = appBO.deleteApp(ids);

                    if (result)
                    {
                        //Tra ve thong bao xoa thanh cong
                        LogStream.Write(GetCurrentUserName(),
                            CommonData.AppName,
                            GetFunction(),
                            CommonData.GetListId(ids),
                            Resources.Localization.ActionDeleteCaption + " - actionDelete");
                        return Json(JsonResponse.Json200(Resources.Localization.Confirm_Delete_Success));
                    }
                    else
                    {
                        //Tra ve thong bao xoa khong thanh cong
                        return Json(JsonResponse.Json500(Resources.Localization.Confirm_Save_Error));
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
            return null;
        }

        /// <summary>
        /// Kiem tra xem ten ung dung da ton tai chua
        /// </summary>
        /// <param name="appName">Ten ung dung duoc kiem tra</param>
        /// <param name="appId">Ma khoa ung dung duoc kiem tra</param>
        /// <returns>Tra ve thong bao da ton tai neu da ton tai ung dung theo dieu kien dau vao</returns>
        public JsonResult CheckExistAppName(string AppName, int? AppId)
        {
            try
            {
                if (string.IsNullOrEmpty(AppName))
                    return Json("Chưa nhập tên");

                ApplicationModel appModel = new ApplicationModel()
                {
                    AppName = AppName
                };
                if (AppId != null && AppId > 0)
                {
                    appModel.AppId = AppId.Value;
                }
                bool check = checkAppExist(appModel);
                if (check)
                {
                    return Json(Resources.Localization.Error_ApplicationNameExist);
                }
                else
                {
                    return Json(true, JsonRequestBehavior.AllowGet);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        /// <summary>
        /// Kiem tra xem Ma ung dung da ton tai chua
        /// </summary>
        /// <param name="appCode">Ma ung dung</param>
        /// <param name="appId">Ma khoa ung dung</param>
        /// <returns>Tra ve thong bao da ton tai neu da ton tai ung dung theo dieu kien dau vao</returns>
        public JsonResult CheckExistAppCode(string AppCode, int? AppId)
        {
            try
            {
                if (string.IsNullOrEmpty(AppCode))
                    return Json("Chưa nhập mã");

                ApplicationModel appModel = new ApplicationModel()
                {
                    AppCode = AppCode
                };
                if (AppId != null && AppId > 0)
                {
                    appModel.AppId = AppId.Value;
                }
                //Kiem tra su ton tai cua ung dung
                bool check = checkAppExist(appModel);
                if (check)
                {
                    //Thong bao ung dung da ton tai
                    return Json(Resources.Localization.Error_ApplicationCodeExist);
                }
                else
                {
                    //Ung dung chua ton tai
                    return Json(true, JsonRequestBehavior.AllowGet);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        /// <summary>
        /// Kiem tra su ton tai cua ung dung
        /// </summary>
        /// <param name="model">Model duoc kiem tra</param>
        /// <returns>True neu Ung dung da ton tai; False neu Ung dung khong ton tai</returns>        
        private bool checkAppExist(ApplicationModel model)
        {
            try
            {
                if (model == null)
                    return false;

                if (Request.IsAjaxRequest())
                {
                    appBO = new ApplicationBO();
                    return appBO.checkAppExist(model.AppId, model.AppCode, model.AppName);
                }
                return false;
            }
            catch
            {                
                throw;
            }
        }

        /// <summary>
        /// Tim kiem ung dung
        /// </summary>
        /// <param name="aModel">Model chua dieu kien tim kiem</param>
        /// <param name="pageIndex">So thu tu cua trang</param>
        /// <param name="currentId">Ma khoa tim kiem</param>
        /// <returns>Page du lieu ung dung</returns>
        private DataPage<ApplicationModel> search(ApplicationModel aModel, int pageIndex, int currentId)
        {
            try
            {
                appBO = new ApplicationBO();
                //Tim kiem ung dung theo dieu kien tim kiem
                var DALModel = appBO.GetDynamicListPaging(aModel.toDALModel(), PageSize, pageIndex);
                var model = new DataPage<ApplicationModel>();
                var lstItem = DALModel.Data;
                foreach (DHQGHN.DAL.Models.Admin.ApplicationModel app in lstItem)
                {
                    model.Data.Add(new ApplicationModel(app));
                }

                ApplicationModel appModel = null;
                if (currentId >= 0 && model.Data.Count > 0)
                {
                    appModel = model.Data.Find(user => user.AppId == currentId);
                    model.CustomData = appModel;
                }
                else
                {
                    model.CustomData = aModel;
                }
                if (model.Data.Count > 0)
                {
                    //Tao component phan trang
                    var pagNative = new Pagination
                    {
                        ActionName = "actionSearch",
                        ModelName = "Application",
                        CurrentPage = pageIndex,
                        InputSearchId = string.Empty,
                        TagetReLoadId = "app-list",

                    };
                    pagNative.TotalRows = model.Data[0].RecordCount;
                    pagNative.CurrentRow = model.Data.Count;
                    ViewBag.Pagination = pagNative;
                }
                return model;
            }
            catch
            {
                throw;
            }
        }

        private string GetFunction()
        {
            return "Quản trị ứng dụng - ApplicationController";
        }
    }
}